import React, {useEffect, useState, useRef} from 'react'
import {Button, Space, Tag} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect, useModel} from 'umi'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import {getCompany} from '@/service/system/company'
import {modelSeriesFun, translateDataToTree} from '@/utils/common/index'
import {getXZCarTypeList} from '@/service/carMessage/list'
import {getTableList} from '@/service/carMessage/licence'
import {uploadFileUrl} from '@/service/common/upload'
import BatchUploadImg from './components/BatchUploadImg'
import Permissions from '@/components/Permissions'
import {downloadDocumentUrl} from '@/service/common/download'
import 'moment/locale/zh-cn'
import {
	carStatus,
	operationType,
	onlineCarLicenseStatus,
	carLicenseStatus,
	carMotorStatus,
	carMainKey,
	carSecondarKey,
	gasCylinderStatus,
} from '../dict'
import {getHolderDictInfo} from '@/service/common'

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}

const renewalDom = (props: {
	user: {orgId: string | number; userName: string; userId: string}
	location: any
}) => {
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const [tableList, setTableList] = useState<any[]>([])
	const [formData, setFormData] = useState<any[]>([])
	const [otherData, setOtherData] = useState<any>()
	const [orgSource, setOrgSource] = useState<any>([])
	const [carTypeList, setCarTypeList] = useState<any>([])
	// 持有方数据
	const [holderDict, setHolderDict] = useState([])
	/** 获取持有方数据 */
	const getHolderDictInfoFun = () => {
		getHolderDictInfo({type: 'holder'}).then((res: any) => {
			if (res?.success) {
				setHolderDict(res?.data)
			}
		})
	}
	useEffect(() => {
		getHolderDictInfoFun()
	}, [])

	// 批量导入车辆图片
	const [isCarImgModalOpen, setIsCarImgModalOpen] = useState(false)

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({
			...params,
			...otherData,
		})
			.then((res: any) => {
				if (res?.success) {
					setTableList(() => res.data.records)
					setTotal(res.data.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	// 列表
	const columns: ColumnsType<TargetAPI.TargetColumns> = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: string, record: any, index: number) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '车辆ID',
			dataIndex: 'carId',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车牌号',
			dataIndex: 'carPlateNo',
			align: 'center',
			width: 140,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '品牌车系车型',
			dataIndex: 'carBrandSeries',
			align: 'center',
			width: 250,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '车辆状态',
			dataIndex: 'carStatus',
			align: 'center',
			width: 150,
			render: (text: number) => (
				<>
					{carStatus?.map((item: {key: number; label: string}) => {
						if (item?.key === text) {
							return <Tag color="processing">{item?.label}</Tag>
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '持有方',
			dataIndex: 'holderName',
			align: 'center',
			width: 150,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '所属公司',
			dataIndex: 'companyName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '所有人',
			dataIndex: 'ownerName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '运营分类',
			dataIndex: 'selfManaged',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{operationType?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '资产所有方',
			dataIndex: 'assertsOwnerName',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '网约车证',
			dataIndex: 'carHailingStatus',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{onlineCarLicenseStatus?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '行驶证',
			dataIndex: 'licenseStatus',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{carLicenseStatus?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},

		{
			title: '气瓶证',
			dataIndex: 'isGasCylinderCar',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{gasCylinderStatus?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '机动车登记证',
			dataIndex: 'carMotorStatus',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{carMotorStatus?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '主钥匙',
			dataIndex: 'carMainKey',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{carMainKey?.map((item: {key: number; label: string}) => {
						if (item?.key === text) {
							return <Tag color="processing">{item?.label}</Tag>
						}
						return ''
					})}
				</>
			),
		},
		{
			title: '副钥匙',
			dataIndex: 'carSecondarKey',
			align: 'center',
			width: 200,
			render: (text: number) => (
				<>
					{carSecondarKey?.map(
						(item: {key: number; label: string}) => {
							if (item?.key === text) {
								return (
									<Tag color="processing">{item?.label}</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '最近盘点时间',
			dataIndex: 'inventoryTime',
			align: 'center',
			width: 200,
			render: (text: string) => <span>{text || '--'}</span>,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text, record: {id: any}) => (
				<div>
					<Permissions permissionID="amc_assetCenter_carMessage_licence_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/licence/view',
									query: {
										id: record.id,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_licence_edit">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/carMessage/licence/edit',
									query: {
										id: record.id,
									},
								})
							}}>
							编辑
						</Button>
					</Permissions>
				</div>
			),
		},
	]

	// 搜索
	const onFinish = (values: any) => {
		setOtherData(() => values)
	}

	// 获取品牌车系
	const onCarTypeListFun = () => {
		getXZCarTypeList().then((res: any) => {
			if (res?.success) {
				setCarTypeList(modelSeriesFun(res.data))
			}
		})
	}

	useEffect(() => {
		onCarTypeListFun()
	}, [])

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
			}
		})
	}

	useEffect(() => {
		onOrgFun()
	}, [props?.user?.orgId])

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [otherData])
	// 重置
	const onReset = () => {
		setOtherData({})
	}

	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'select',
						label: '持有方',
						name: 'holderId',
						key: 'holderId',
						keys: 'value',
						title: 'valueName',
						items: [...holderDict],
					},
					{
						type: 'select',
						key: 'fashionId',
						name: 'fashionId',
						label: '品牌车系车型',
						keys: 'id',
						title: 'fullName',
						items: [...carTypeList],
					},
					{
						type: 'input',
						key: 'carId',
						name: 'carId',
						label: '车辆ID',
						rules: [
							{
								pattern: /^[0-9]*$/,
								message: '车辆ID请输入数字',
							},
						],
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'input',
						key: 'carPlateNo',
						name: 'carPlateNo',
						label: '车牌号',
					},
					{
						type: 'select',
						key: 'carStatus',
						name: 'carStatus',
						label: '车辆状态',
						keys: 'key',
						title: 'label',
						items: [...carStatus],
					},
					{
						type: 'select',
						key: 'selfManaged',
						name: 'selfManaged',
						label: '运营分类',
						keys: 'key',
						title: 'label',
						items: [...operationType],
					},
				],
			},
			{
				type: 'group',
				key: 'group3',
				groupItems: [
					{
						type: 'treeSelect',
						key: 'companyId',
						name: 'companyId',
						label: '资产所有方',
						keys: 'id',
						title: 'name',
						treeData: [...orgSource],
					},
					{
						type: 'select',
						key: 'carHailingStatus',
						name: 'carHailingStatus',
						label: '网约车证',
						keys: 'key',
						title: 'label',
						items: [...onlineCarLicenseStatus],
					},
					{
						type: 'select',
						key: 'licenseStatus',
						name: 'licenseStatus',
						label: '行驶证',
						keys: 'key',
						title: 'label',
						items: [...carLicenseStatus],
					},
				],
			},
			{
				type: 'group',
				key: 'group4',
				groupItems: [
					{
						type: 'select',
						key: 'carMotorStatus',
						name: 'carMotorStatus',
						label: '机动车登记证',
						keys: 'key',
						title: 'label',
						items: [...carMotorStatus],
					},
					{
						type: 'select',
						key: 'gasCylinderStatus',
						name: 'gasCylinderStatus',
						label: '气瓶证',
						keys: 'key',
						title: 'label',
						items: [...gasCylinderStatus],
					},
					{
						type: 'select',
						key: 'carMainKey',
						name: 'carMainKey',
						label: '主钥匙',
						keys: 'key',
						title: 'label',
						items: [...carMainKey],
					},
				],
			},
			{
				type: 'group',
				key: 'group5',
				groupItems: [
					{
						type: 'select',
						key: 'carSecondarKey',
						name: 'carSecondarKey',
						label: '副钥匙',
						keys: 'key',
						title: 'label',
						items: [...carSecondarKey],
					},
					{},
					{},
				],
			},
		]
		setFormData(formItems)
	}, [orgSource, carTypeList])

	// 批量导入车辆图片取消
	const carImgModalOpen = () => {
		setIsCarImgModalOpen(() => false)
	}
	const resetList = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_assetCenter_carMessage_licence_batchImportImg">
						<Button
							type="primary"
							ghost
							size="small"
							onClick={() => {
								setIsCarImgModalOpen(() => true)
							}}>
							批量上传图片
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_licence_export">
						<Button
							ghost
							size="small"
							className="btn_warning"
							onClick={() => {
								downloadDocumentUrl({
									resourceId: '117',
									queryDesc: '证照管理导出,resourceId:117',
									queryParam: otherData,
								})
							}}>
							导出
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					kid="carId"
					params={params}
					columns={columns}
					pagination
					total={total}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={tableList}
				/>
			</div>
			<BatchUploadImg
				title="批量上传图片"
				isModalOpen={isCarImgModalOpen}
				setIsModalOpen={carImgModalOpen}
				accept={['image/jpeg', 'image/png']}
				moreNum={50}
				fileNmae={fileName}
				fileData={{
					modelName: 'carList',
					targetAttr: 0,
				}}
				resetList={resetList}
				uploadFileUrl={uploadFileUrl}
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(renewalDom)
